<?php

class Privacy_Api_Privacy
{
	/**
	 * @param  Database_Model_Item    $resource
	 * @param  string                 $action
	 * @param  int                    $value
	 * @return TRUE/FALSE
	 */
	function setPrivacy($resource, $action, $value, $params = array())
	{
		if (!$resource instanceof Database_Model_Item)
		{
			return FALSE;
		}

		if (!is_string($action))
		{
			return FALSE;
		}

		$table = Nuo::getTable('privacy');

		$params = (array)$params;
		$value = (int)$value;

		$select = $table -> select() -> where('resource_id=?', $resource -> getItemId()) -> where('action=?', $action);

		$obj = $table -> fetchRow($select);

		if (!$obj)
		{
			$obj = $table -> fetchNew();
			$obj -> resource_id = $resource -> getItemId();
			$obj -> action = $action;
		}

		$obj -> value = $value;
		$obj -> params = json_encode($params);
		$obj -> save();

		return TRUE;
	}

	/**
	 * @param  Database_Model_Item    $resource
	 * @param  string                 $action
	 * @return array(value=>int, params=>array{int,})
	 */
	function getPrivacy($resource, $action)
	{
		$table = Nuo::getTable('privacy');
		$select = $table -> select() -> where('resource_id=?', $resource -> getItemId()) -> where('action=?', (string)$action);

		$obj = $table -> fetchRow($select);

		if ($obj)
		{
			return array(
				$obj -> value,
				json_decode($obj -> params, 1)
			);
		}

		return array(
			0,
			0
		);
	}

	/**
	 * @param Database_Model_Item
	 * @return TRUE/FALSE
	 */
	function checkPrivacy($resource, $action)
	{
		if (!$resource)
		{
			return array(
				0,
				0
			);
		}

		$obj = $resource -> getProxy();

		if (!is_object($obj))
		{
			return FALSE;
		}

		list($value, $params) = $this -> getPrivacy($obj, $action);

		$value = $privacy['value'];

		if (0 == $value)
		{
			return TRUE;
		}

		$member = Nuo::getUser();

		$memberId = $member -> getItemId();

		/**
		 * owner pass all rule
		 */
		if ($obj -> isOwner($member))
		{
			return TRUE;
		}

		/**
		 * members
		 */
		if ($value == 1 or $value == 2)
		{
			$isMember = Nuo::getApi('membership') -> isMember($obj, $member);

			if ($privacy == 1 || $isMember)
			{
				return $isMember;
			}
		}

		/**
		 * members of members
		 */
		if ($value == 2)
		{
			// friends of members of item
			
			return Nuo::getApi('membership') -> isMemberOfMember($obj, $member);
		}

		// do not check privacy = 3 because it's checked before.

		// in custom lists
		if ($value == 4)
		{
		}

		// custom networks
		if ($value == 5)
		{
		}
		return FALSE;
	}

}
